#version grafana 11 20240816
from grafana_dashboard import dashboard_class
import json
import os
import copy

# Grafana的URL和登录凭据  
grafana_host_url = 'http://10.223.38.23:3000'  
user_name = 'sumz'  
pass_word = 'Sumz'  

# 读取接口信息文件，根据可变信息，生成告警与图表
current_directory = os.path.dirname(os.path.abspath(__file__))
file_path = os.path.join(current_directory, 'urllist.json')  
with open(file_path, 'r', encoding='utf-8') as file:  
    data = json.load(file)  
endpoints = data['items']

## 查询所有监控规则
from grafana_alert import alert_class
test = alert_class.GrafanaAlert(grafana_host_url, 'glsa_esbINXxUe28xgjlp6lqZdrv3vnzqM7XV_eb38effe')
response_json = test.get_alert_rules()  
for response_json_one in response_json:    # 循环删除
    uid = response_json_one["uid"]
    test.delete_alert_rules(uid)
# 创建监控
test = alert_class.GrafanaAlert(grafana_host_url, 'glsa_esbINXxUe28xgjlp6lqZdrv3vnzqM7XV_eb38effe')
folderUID = "cdu2geontnke8a"
datasourceUid ="adtaok5che4n4b"
for endpoints_one in endpoints:
    test.create_alert_rules(endpoints_one, folderUID, datasourceUid)

## 查询仪表盘，替换其中图表后，提交创建/修改
test = dashboard_class.GrafanaDashboard(grafana_host_url, 'glsa_esbINXxUe28xgjlp6lqZdrv3vnzqM7XV_eb38effe')
test_data = test.get_alert_rules("ddtztj13cg3y8d")
dashboard_data = test_data["dashboard"]
dashboard_data["panels"] = []   # 清空仪表板中的面板

file_dashboard_panels_temp_path = os.path.join(current_directory, "grafana_dashboard", 'dashboard_panels_temp.json')   # 读取导出的面板模板内容, 可先手动创建模板，导出JSON，然后动态生成面板
with open(file_dashboard_panels_temp_path, 'r', encoding='utf-8') as dashboard_panels_temp_file:  
    dashboard_panels_temp_data_dict = json.load(dashboard_panels_temp_file)

x = 0  # 面板x位置
y = 0  # 面板y位置
for endpoints_one in endpoints:   # 循环替换仪表模板内容，生成新的面板
    dashboard_panels_temp_data_dict_copy = copy.deepcopy(dashboard_panels_temp_data_dict)

    dashboard_panels_temp_data_dict_copy["targets"][0]["expr"] = endpoints_one["name"]
    dashboard_panels_temp_data_dict_copy["title"] = endpoints_one["title"]

    if x <= 24:   # 每个面板位置计算，此例子都是接口监控，为3x3的面板，仪表宽度为24，动态生成每个面板位置
        grid_pos = {"h": 3, "w": 3, "x": x, "y": y}
        dashboard_panels_temp_data_dict_copy["gridPos"] = grid_pos
        x += 3
    else:
        y += 3
        x = 3

    dashboard_data["panels"].append(dashboard_panels_temp_data_dict_copy)  # 循环面板添加到仪表板内

test.update_dashboard(dashboard_data)